package mwa.cs.rc.ctrl;

import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

import mwa.cs.dao.CustHHDAO;
import mwa.cs.dao.RcTransMDAO;
import mwa.cs.dao.ReceiveCodeDAO;
import mwa.cs.dao.SMErrorLogDAO;
import mwa.cs.dao.UserLoginDAO;
import mwa.cs.database.Database;
import mwa.cs.model.RcTransD;
import mwa.cs.model.RcTransM;
import mwa.cs.util.JDate;


public class CS54001Srvl extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private int vnSiteId;
	private int vnUserId;
	private String vaUrlAddress;
	private String vaAgentBrowser;

    public CS54001Srvl() {
        super();
    }
    
	@SuppressWarnings({ "unused" })
	public void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/JSON");
		HttpSession session = request.getSession();
		vnSiteId = Integer.parseInt(request.getSession().getAttribute("site_id").toString());
		vnUserId = Integer.parseInt(request.getSession().getAttribute("user_id").toString());
		vaUrlAddress = request.getParameter("url_address");
		vaAgentBrowser = request.getParameter("agent_browser");
		String vaBtnSave = request.getParameter("btn_save");
		request.setCharacterEncoding("UTF-8");
   		response.setCharacterEncoding("UTF-8");
   		response.setContentType("text/JSON");
		if(request.getParameter("process_type")!=null){
			if (request.getParameter("process_type").equals("getEmployee")) {
				getExployee(request, response);
				return;
			}else if(request.getParameter("process_type").equals("getReceive")){
				getReceiveCode(request, response);
				return;
			}
		}
		
		if ( vaBtnSave == null){
			vaBtnSave ="no";
		}
		String vaStatusSaveButton = "btn_enable";
		Database db = new Database();
		RcTransMDAO voRcTransMDAO = new RcTransMDAO(db);
		String vaErrorMsg = "no";
		int vnCancelResult  = voRcTransMDAO.findExistDataIsAlreadyClosed(vnSiteId, vnUserId);
		int voAlreayClosedResult =  voRcTransMDAO.findExistDataIsAlreadyClosed(vnSiteId, vnUserId);
		int voTransactionResult =  voRcTransMDAO.findExistTransactionData(vnSiteId, vnUserId);
		String vaAlreadyColse = "no";
		if ( vaBtnSave.trim().equals("no") && voAlreayClosedResult == 0){
			if (voTransactionResult != 0){
		    	loadDataFirstInComing(request, response, vaStatusSaveButton, vaAlreadyColse);
			} else {
				vaErrorMsg = "yes";
			}	
		} else {
			// มีการปิดการรับเงินแล้ว
			boolean vbPassSaveButton  = false ;
			if ( vaBtnSave != null && vaBtnSave.trim().equals("yes")){
				// update close_date in rc_rans_m
				try {
					db.beginTransaction();
					voRcTransMDAO.UpdateColseDateInDatabase(vnSiteId,vnUserId);
		    		db.commit();
					vaAlreadyColse = "yes";
					vaStatusSaveButton = "btn_disable";
					vbPassSaveButton = true;
				} catch (Exception e) {
					SMErrorLogDAO.getInstance().addLog(0, "CS54001", JDate.getDate(), JDate.getTime(),vnUserId, "CS54001Srvl", e.getMessage(),vaUrlAddress, vaAgentBrowser);
		    		db.rollback();
		    	} 
		    	loadDataFirstInComing(request, response, vaStatusSaveButton, vaAlreadyColse);
	    		request.setAttribute("vaStatusUpdate", "success");
				request.setAttribute("vaPageSetting", "2");
				request.setAttribute("vaStatusSaveButton", vaStatusSaveButton);
			}
			
			if ( vbPassSaveButton == false ){
				vaAlreadyColse = "yes";
				vaStatusSaveButton = "btn_disable";
		    	loadDataFirstInComing(request, response, vaStatusSaveButton, vaAlreadyColse);
				request.setAttribute("vaStatusSaveButton", vaStatusSaveButton);
			}
		}
		db.close();
		
		request.setAttribute("vaErrorMsg", vaErrorMsg);
    	RequestDispatcher voRequestDispatcher = request.getRequestDispatcher("CS54001.jsp");
    	voRequestDispatcher.forward(request, response); 
	}

	private void loadDataFirstInComing(HttpServletRequest request, HttpServletResponse response, String vaStatusSaveButton, String vaAlreadyColse) throws ServletException, IOException {
		Database db = new Database();
		RcTransMDAO voRcTransMDAO = new RcTransMDAO(db);
		ReceiveCodeDAO voReceiveCodeDAO = new ReceiveCodeDAO(db);
		double vnSumRow21 = 0.00;
		// Step1 ReceiveCode != 21
		ArrayList<RcTransM> voStepOneReceiveCodeNot21List = new ArrayList<RcTransM>();
		List<Map<String ,Object>> voVatAndBillAmount = null;
		List<Map<String ,Object>> voReceiveCodeIs21 = null ;
		double vnTotalPenalty = 0.0;
		if ( vaAlreadyColse.equals("yes")){
			voVatAndBillAmount = voRcTransMDAO.sumVatAmountAndBillAmountIsCurrentDate(vnSiteId, vnUserId);
			voReceiveCodeIs21 = voRcTransMDAO.sumVatAmountAndBillAmountReceiveCodeIs21IsCurrentDate(vnSiteId, vnUserId);
			vnTotalPenalty = voRcTransMDAO.sumPenaltyForCancelByReceiveEmployee(vnSiteId, vnUserId);
		} else {
			vnTotalPenalty = voRcTransMDAO.sumPenaltyByReceiveEmployee(vnSiteId, vnUserId);
			voVatAndBillAmount = voRcTransMDAO.sumVatAmountAndBillAmount(vnSiteId, vnUserId);
			voReceiveCodeIs21 = voRcTransMDAO.sumVatAmountAndBillAmountReceiveCodeIs21(vnSiteId, vnUserId);
		}
		
		for (int i = 0; i < voVatAndBillAmount.size(); i++ ){
			Map<String, Object> voObject = voVatAndBillAmount.get(i);
			String vaReceiveCodeTemp = voObject.get("RECEIVE_CODE").toString();
			vaReceiveCodeTemp = voReceiveCodeDAO.getDescriptionByReceiveCode(vnSiteId, vaReceiveCodeTemp);
			double vnVatTotal = Double.parseDouble(((BigDecimal)voObject.get("VAT_TOTAL")).toString());
			double vnBillAmountTotal = Double.parseDouble(((BigDecimal)voObject.get("BILL_TOTAL")).toString());
			vnSumRow21 += (vnBillAmountTotal-vnVatTotal);
			RcTransM voRcTransM = new RcTransM();
			voRcTransM.setVaReceiveDate(vaReceiveCodeTemp);
			voRcTransM.setVnVatAmount(vnVatTotal);
			voRcTransM.setVnGrossAmount(vnBillAmountTotal);
			voStepOneReceiveCodeNot21List.add(voRcTransM);
		}
		// Step1 ReceiveCode == 21
		RcTransD voStepOneReceiveCode21 = new RcTransD();
		for (int i = 0; i < voReceiveCodeIs21.size(); i++ ){
			Map<String, Object> voObject = voReceiveCodeIs21.get(i);
			//String vaReceiveCodeTemp = voObject.get("RECEIVE_CODE").toString();
			//voReceiveCodeDAO.getDescriptionByReceiveCode(vnSiteId, vaReceiveCodeTemp);
			// vaReceiveCode = vaReceiveCodeTemp;
			double vnVatTotal = Double.parseDouble(((BigDecimal)voObject.get("VAT_TOTAL")).toString());
			double vnAmount = Double.parseDouble(((BigDecimal)voObject.get("CHARGE_AND_FEE")).toString());
			double vnGarbage = Double.parseDouble(((BigDecimal)voObject.get("GARGEBAGE")).toString());
			double vnWateWater = Double.parseDouble(((BigDecimal)voObject.get("WASTEWATER")).toString());
			double vnOther = Double.parseDouble(((BigDecimal)voObject.get("OTHER_CHARGE")).toString());
			vnSumRow21 = vnVatTotal + vnAmount + vnGarbage + vnWateWater + vnOther + vnSumRow21;
			//voStepOneReceiveCode21.setVaReceiveCode(vaReceiveCode);
			voStepOneReceiveCode21.setVnVatAmount(vnVatTotal);
			voStepOneReceiveCode21.setVnBillAmount(vnAmount);
			voStepOneReceiveCode21.setVnGarbageCharge(vnGarbage);
			voStepOneReceiveCode21.setVnWasteWaterCharge(vnWateWater);
			voStepOneReceiveCode21.setVnOtherCharge(vnOther);
		}
		request.setAttribute("voStepOneReceiveCodeNot21List", voStepOneReceiveCodeNot21List);
		request.setAttribute("voStepOneReceiveCode21", voStepOneReceiveCode21);
		request.setAttribute("vnTotalPenalty", vnTotalPenalty);
		request.setAttribute("vnSumRow21", vnSumRow21);	
			
		// Step 2 Close Already get money data
		String vaStep2ErrorMsg = "hide";
		List<Map<String, Object>> voRcTransMAlreadyGetMoney ;
		voRcTransMAlreadyGetMoney = voRcTransMDAO.findRcTransMByRecieveEmployee(vnSiteId);		
		String vaEmployee = "",vaEmployeeId = "";
		ArrayList<RcTransM> voAlreadyGetMoneyList = new ArrayList<RcTransM>();
		for (int i = 0; i < voRcTransMAlreadyGetMoney.size(); i++ ){
			RcTransM voRcTransM = new RcTransM();
			Map<String, Object> voObject = voRcTransMAlreadyGetMoney.get(i);
			vaEmployeeId = ((BigDecimal)voObject.get("RECEIVE_EMPLOYEE")).toString();
			vaEmployee = voObject.get("EMP_NAME").toString();
			double vaGrossAmount = Double.parseDouble(((BigDecimal) voObject.get("EMP_GROSS")).toString());	
//			double vaPenalty = Double.parseDouble(((BigDecimal) voObject.get("RC_PENALTY")).toString());
			voRcTransM.setVnReceiveEmployee(Integer.parseInt(vaEmployeeId));
			voRcTransM.setVaAccount(vaEmployee);
			voRcTransM.setVnGrossAmount(vaGrossAmount);
			voAlreadyGetMoneyList.add(voRcTransM);
		}
		voAlreadyGetMoneyList.trimToSize();
		// Step2 Not close get money data
		List<Map<String, Object>> voRcTransMNotGetMoney ;
		voRcTransMNotGetMoney = voRcTransMDAO.findRcTransMByRecieveEmployeeNull(vnSiteId);
		ArrayList<RcTransM> voNotGetMoneyList = new ArrayList<RcTransM>();
		if ( voRcTransMNotGetMoney.size() != 0){
			for (int i = 0; i < voRcTransMNotGetMoney.size(); i++ ){
				RcTransM voRcTransM = new RcTransM();
				Map<String, Object> voObject2 = voRcTransMNotGetMoney.get(i); 
				vaEmployeeId = ((BigDecimal)voObject2.get("RECEIVE_EMPLOYEE")).toString();
				vaEmployee = voObject2.get("EMP_NAME").toString();
				double vaGrossAmount = Double.parseDouble(((BigDecimal) voObject2.get("EMP_GROSS")).toString());	
//				double vaPenalty = Double.parseDouble(((BigDecimal) voObject2.get("RC_PENALTY")).toString());
				voRcTransM.setVnReceiveEmployee(Integer.parseInt(vaEmployeeId));
				voRcTransM.setVaAccount(vaEmployee);
				voRcTransM.setVnGrossAmount(vaGrossAmount);
				voNotGetMoneyList.add(voRcTransM);
			}
		}
		voNotGetMoneyList.trimToSize();
		db.close();
		if (voAlreadyGetMoneyList.size() == 0 && voNotGetMoneyList.size() == 0){
			vaStep2ErrorMsg = "show";
		}
		request.setAttribute("vaStep2ErrorMsg", vaStep2ErrorMsg);
		request.setAttribute("voAlreadyGetMoneyList", voAlreadyGetMoneyList);
		request.setAttribute("voNotGetMoneyList", voNotGetMoneyList);
	}
	
	@SuppressWarnings("unchecked")
	public void getExployee(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	Database db = new Database();

		try {
			UserLoginDAO voUserLogin = new UserLoginDAO(db);
			List<Map<String, Object>> voResult = voUserLogin.findAllUserNameBySiteId(vnSiteId);
	
			String[] vaValue = new String[voResult.size()];
			String[] vaMessage = new String[voResult.size()];

			for (int i = 0; i < voResult.size(); i++) {
				Map<String, Object> voObject = voResult.get(i);	
				vaValue[i] = (String) voObject.get("USER_ID").toString(); 
				vaMessage[i] = ((String)voObject.get("USER_PNAME").toString())+" "
								+((String)voObject.get("USER_FNAME").toString())+" "
								+((String)voObject.get("USER_LNAME").toString());	
			}
			
			JSONObject voObject = new JSONObject();
			JSONArray voList = new JSONArray();
			PrintWriter out = response.getWriter();
			if (vaMessage != null) {
				for (int i = 0; i < vaMessage.length; i ++) {
					voList.add(vaMessage[i]);
				}
			}
			voObject.put("messages", voList);
			JSONArray voList2 = new JSONArray();
			if (vaValue != null) {
				for (int i = 0; i < vaValue.length; i ++) {
					voList2.add(vaValue[i]);
				}
			}

			voObject.put("values", voList2);
			String[] vaDay = getMaxDayInCustHH(vnSiteId);
			voObject.put("vaDay", vaDay[0]);
			voObject.put("vaMonth", vaDay[1]);
			voObject.put("vaYear", vaDay[2]);

			out.print(voObject.toJSONString());
		} catch (Exception e) {
			e.printStackTrace();
		} finally{
			db.close();
		}
	}

    public void getReceiveCode(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	Database db = new Database();
    	try {
    		ReceiveCodeDAO voReceiveCode = new ReceiveCodeDAO(db);
			List<Map<String, Object>> voResult = voReceiveCode.findReceive_CodeBySite(vnSiteId);
	
			String[] vaValue = new String[voResult.size()];
			String[] vaMessage = new String[voResult.size()];

			for (int i = 0; i < voResult.size(); i++) {
				Map<String, Object> voObject = voResult.get(i);	
				vaValue[i] = (String) voObject.get("RECEIVE_CODE").toString(); 
				vaMessage[i] = (String)voObject.get("DESCRIPTION").toString();	
			}
			
			JSONObject voObject = new JSONObject();
			JSONArray voList = new JSONArray();
			PrintWriter out = response.getWriter();
			if (vaMessage != null) {
				for (int i = 0; i < vaMessage.length; i ++) {
					voList.add(vaMessage[i]);
				}
			}
			voObject.put("messages", voList);
			JSONArray voList2 = new JSONArray();
			if (vaValue != null) {
				for (int i = 0; i < vaValue.length; i ++) {
					voList2.add(vaValue[i]);
				}
			}

			voObject.put("values", voList2);

			out.print(voObject.toJSONString());
		} catch (Exception e) {
			e.printStackTrace();
		} finally{
			db.close();
		}
    }
    
    public String[] getMaxDayInCustHH(int pnSiteId) {
    	Database db = new Database();
		CustHHDAO voCustHHManagement = new CustHHDAO(db);
		String vaMaxMonth = null,vaMaxDay = null, vaMaxYear = null;

			vaMaxDay = JDate.getDay();
			vaMaxMonth = JDate.getMonth();
			vaMaxYear = JDate.getYear();
		
		String[] vaDay = new String[3];
		vaDay[0] = vaMaxDay;
		vaDay[1] = vaMaxMonth;
		vaDay[2] = vaMaxYear;
		db.close();
		return vaDay;
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);

	}


	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);

	}

}
